"""
从 一百万位 pi 里找到自己的出生年月
"""

import re
import time
import datetime 
 
def get_diff_days_2(date_str1, date_str2):
    """
    两天的天数差距
    """
    time1 = time.strptime(date_str1, "%Y%m%d")
    time2 = time.strptime(date_str2, "%Y%m%d")
    # 比较日期
    date1 = datetime.datetime(time1[0], time1[1], time1[2])
    date2 = datetime.datetime(time2[0], time2[1], time2[2])
    diff_days = (date2 - date1).days
    return abs(diff_days)

if __name__ == '__main__':
    with open('./pi.txt', 'r', encoding='utf-8') as f:
        try:
            pi = f.read()
            # 19[8-9][0-9]((0[1-9]|1[0-2])(0[1-9]|1[0-9]|2[0-8])|(0[13-9]|1[0-2])(29|30)|(0[13578]|1[02])31) 除闰年的 2月 29 日外的其它所有日期
            # (19(8[048]|9[26]))0229 四年一闰,1980-2000之间没有400和100能整除的，所以不考虑其他情况
            pattern1 = re.compile('19[8-9][0-9]((0[1-9]|1[0-2])(0[1-9]|1[0-9]|2[0-8])|(0[13-9]|1[0-2])(29|30)|(0[13578]|1[02])31)|(19(8[048]|9[26]))0229')
            match_list2 = re.finditer(pattern1, pi)
            min_value =9999999
            result1 = []
            result2 = (None, None)
            for res in match_list2:
                start = res.start()
                value = res.group()
                result1.append((start, value))
                dis = get_diff_days_2(value, '19920214')
                if dis < min_value: 
                    min_value = dis
                    result2 = (start, value)

            pattern3 = re.compile('19[6-9][0-9]|200[0-9]|201[0-9]|202[0-1]')
            match_list3 = pattern3.finditer(pi)
            result3 = [(res.start(), res.group()) for res in match_list3]
        except Exception as e:
            print(e)
     
        print("符合年月日规则的字符(起始位置,值):\n", result1)
        print("找到里自己生日19920214最近的一个(起始位置,值):\n", result2)
        print("年份1960--2021的正则匹配结果(起始位置,值):\n", result3)
